import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final GlobalKey _formKey = GlobalKey<FormState>();
  late String _name='', _phoneNumber='', _password='', _confirmPassword='';
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: kToolbarHeight), // 距离顶部一个工具栏的高度
          Row(
              children: [
          IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          buildTitle(),]), // Login
          buildTitleLine(), // Login下面的下划线
          Expanded(
            child: SingleChildScrollView(
              child: Form(
                key: _formKey,
                autovalidateMode: AutovalidateMode.onUserInteraction,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Column(
                    children: [
                      const SizedBox(height: 20),
                      buildNameTextField(),
                      const SizedBox(height: 20),
                      buildPhoneNumberTextField(),
                      const SizedBox(height: 20),
                      buildPasswordTextField(context),
                      const SizedBox(height: 20),
                      buildConfirmPasswordTextField(context),
                      const SizedBox(height: 40),
                      buildRegisterButton(context),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildNameTextField() {
    return TextFormField(
      decoration: const InputDecoration(labelText: '昵称'),
      validator: (v) {
        if (v!.isEmpty) {
          return '请输入昵称';
        }
      },
      onSaved: (v) => _name = v!,
    );
  }

  Widget buildPhoneNumberTextField() {
    return TextFormField(
      decoration: const InputDecoration(labelText: '手机号'),
      validator: (v) {
        var phoneReg = RegExp(r"^(1[3-9])\d{9}$");
        if (!phoneReg.hasMatch(v!)) {
          return '请输入正确的手机号码';
        }
      },
      onSaved: (v) => _phoneNumber = v!,
    );
  }

  Widget buildPasswordTextField(BuildContext context) {
    return TextFormField(
      obscureText: _isObscure,
      decoration: InputDecoration(
        labelText: "密码",
        suffixIcon: IconButton(
          icon: Icon(
            Icons.remove_red_eye,
            color: _eyeColor,
          ),
          onPressed: () {
            setState(() {
              _isObscure = !_isObscure;
              _eyeColor =
              (_isObscure ? Colors.grey : Theme.of(context).iconTheme.color)!;
            });
          },
        ),
      ),
      validator: (v) {
        if (v!.isEmpty) {
          return '请输入密码';
        }
      },
      onSaved: (v) => _password = v!,
    );
  }

  Widget buildConfirmPasswordTextField(BuildContext context) {
    return TextFormField(
      obscureText: _isObscure,
      decoration: InputDecoration(
        labelText: "确认密码",
        suffixIcon: IconButton(
          icon: Icon(
            Icons.remove_red_eye,
            color: _eyeColor,
          ),
          onPressed: () {
            setState(() {
              _isObscure = !_isObscure;
              _eyeColor =
              (_isObscure ? Colors.grey : Theme.of(context).iconTheme.color)!;
            });
          },
        ),
      ),
      validator: (v) {
        if (v!.isEmpty) {
          return '请再次输入密码';
        } else if (v != _password) {//有问题
          print(_password);
          print("aaa");
          print(v);
          return '两次密码输入不一致';
        }
      },
      onSaved: (v) => _confirmPassword = v!,
    );
  }

  Widget buildRegisterButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45,
        width: 270,
        child: ElevatedButton(
          style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all(Colors.green),
            shape: MaterialStateProperty.all(
              const StadiumBorder(side: BorderSide(style: BorderStyle.none)),
            ),
          ),
          child: Text(
            '注册',
            style: Theme.of(context).primaryTextTheme.headline5,
          ),
          onPressed: () {
            if ((_formKey.currentState as FormState).validate()) {
              (_formKey.currentState as FormState).save();
              print('bbb');
              _registerUser(_phoneNumber, _password, _name);
              print('Name: $_name, Phone Number: $_phoneNumber, Password: $_password');
            }
          },
        ),
      ),
    );
  }
}
Future<void> _registerUser(String phone, String password, String name) async {
  try {
    final body = jsonEncode({
      'phone': phone,
      'password': password,
      'name': name,
    });

    var headers = {"Content-Type": "application/json"};

    var response = await http.post(
      Uri.parse('http://10.197.88.206:8080/user/register'),
      headers: headers,
      body: body,
    );
    print(body);

    if (response.statusCode == 200) {
      final responseData = jsonDecode(response.body);
      if (responseData['code'] == '200') {
        print('注册成功');
        // 这里可以根据需要执行一些操作，比如页面跳转等
      } else {
        print('注册失败: ${responseData['msg']}');
      }
    } else {
      print('HTTP错误: ${response.statusCode}');
    }
  } catch (err) {
    print('注册失败，发生错误: $err');
  }
}

Widget buildTitleLine() {
  return Padding(
      padding: const EdgeInsets.only(left: 80.0, top: 4.0),
      child: Align(
        alignment: Alignment.bottomLeft,
        child: Container(
          color: Colors.black,
          width: 40,
          height: 2,
        ),
      ));
}

Widget buildTitle() {
  return const Padding(
      padding: EdgeInsets.all(8),
      child: Text(
        '注册',
        style: TextStyle(fontSize: 42),
      ));
}
